//
//  ChatInputView.swift
//  TestIos
//
//  Created by 李亚东 on 2025/11/4.
//  Copyright © 2025 Liyadong. All rights reserved.
//

import UIKit
import SnapKit

protocol ChatInputViewDelegate: AnyObject {
    func chatInputView(_ inputView: ChatInputView, didSendMessage message: String)
}

class ChatInputView: UIView {
    
    // MARK: - UI Components
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 1.0)
        view.layer.borderWidth = 0.5
        view.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.3).cgColor
        return view
    }()
    
    private let textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.layer.cornerRadius = 20
        textView.layer.borderWidth = 0.5
        textView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.3).cgColor
        textView.textContainerInset = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12)
        textView.backgroundColor = .white
        textView.returnKeyType = .send
        textView.textColor = UIColor.black
        textView.enablesReturnKeyAutomatically = true
        return textView
    }()
    
    private let sendButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = UIColor(red: 0.2, green: 0.6, blue: 1.0, alpha: 1.0)
        button.layer.cornerRadius = 20
        button.layer.masksToBounds = true
        button.isEnabled = false
        button.alpha = 0.5
        return button
    }()
    
    // MARK: - Properties
    weak var delegate: ChatInputViewDelegate?
    private var textViewHeightConstraint: Constraint?
    private var isSendEnabled: Bool = true  // 是否允许发送消息
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func setupUI() {
        addSubview(containerView)
        containerView.addSubview(textView)
        containerView.addSubview(sendButton)
        
        // 使用 SnapKit 设置布局
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        textView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.height.greaterThanOrEqualTo(40)
            make.height.lessThanOrEqualTo(100)
            // 保存高度约束引用，用于动态更新（需要在链式调用末尾添加 .constraint）
            textViewHeightConstraint = make.height.equalTo(40).constraint
        }
        
        sendButton.snp.makeConstraints { make in
            make.left.equalTo(textView.snp.right).offset(8)
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalTo(textView)
            make.width.equalTo(60)
            make.height.equalTo(40)
        }
    }
    
    private func setupActions() {
        sendButton.addTarget(self, action: #selector(sendButtonTapped), for: .touchUpInside)
        textView.delegate = self
        
        // 监听文本变化
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(textViewDidChange),
            name: UITextView.textDidChangeNotification,
            object: textView
        )
    }
    
    // MARK: - Actions
    @objc private func sendButtonTapped() {
        guard let text = textView.text, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            return
        }
        
        let message = text.trimmingCharacters(in: .whitespacesAndNewlines)
        delegate?.chatInputView(self, didSendMessage: message)
        textView.text = ""
        updateSendButtonState()
        updateTextViewHeight()
        textView.endEditing(true)
    }
    
    @objc private func textViewDidChange() {
        updateSendButtonState()
        updateTextViewHeight()
    }
    
    private func updateSendButtonState() {
        let hasText = !(textView.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
        sendButton.isEnabled = isSendEnabled && hasText
        sendButton.alpha = (isSendEnabled && hasText) ? 1.0 : 0.5
    }
    
    private func updateTextViewHeight() {
        let size = textView.sizeThatFits(CGSize(width: textView.frame.width, height: .greatestFiniteMagnitude))
        let newHeight = min(max(size.height, 40), 100)
        
        // 使用 SnapKit 更新约束
        textViewHeightConstraint?.update(offset: newHeight)
        
        UIView.animate(withDuration: 0.2) {
            self.layoutIfNeeded()
        }
    }
    
    // MARK: - Public Methods
    func clearText() {
        textView.text = ""
        updateSendButtonState()
        updateTextViewHeight()
    }
    
    func becomeFirstResponder() {
        textView.becomeFirstResponder()
    }
    
    func resignFirstResponder() {
        textView.resignFirstResponder()
    }
    
    /// 设置是否允许发送消息（用于禁用发送功能，但不禁止输入）
    func setSendEnabled(_ enabled: Bool) {
        isSendEnabled = enabled
        // 不设置 textView.isEditable，允许用户继续输入
        
        // 更新按钮状态
        updateSendButtonState()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - UITextViewDelegate
extension ChatInputView: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            sendButtonTapped()
            return false
        }
        return true
    }
}

